<template>
  <m-container class="out-work-add">
    <m-steps :current="current" class="steps">
      <m-step title="出库单信息">
        <view class="circle active">1</view>
      </m-step>
      <m-step title="出库单明细">
        <view class="circle" :class="{ active: current === 1 }">2</view>
      </m-step>
    </m-steps>

    <m-cell-group class="box" size="sm" v-if="current === 0" weight="label">
      <m-cell label="出库单信息" size="xs" :border="false" />
      <m-cell title="出库单编号" size="xs">
        <view slot="center" class="center">
          <u-input v-model="form.outOrderCode" type="text" :border="false" placeholder="请输入出库单编号" />
        </view>
      </m-cell>
      <m-cell title="主题" size="xs">
        <view slot="center" class="center">
          <u-input v-model="form.theme" type="text" :border="false" placeholder="请输入主题" />
        </view>
      </m-cell>
      <m-cell title="申请人" class="disabled" size="xs">
        <view slot="center" class="center">{{ userList.map[form.operName] }}</view>
      </m-cell>
      <m-cell
        title="审核人"
        is-link
        @click="handleSelectDict('userList', '选择审核人')"
        :desc="userList.map[form.auditName]"
        size="xs"
      ></m-cell>
      <m-cell title="出库类型" class="disabled" size="xs">
        <view slot="center" class="center">{{ dicts['out_order_source_type'].map[form.sourceType] }}</view>
      </m-cell>
      <!-- <m-cell title="项目" is-link @click="handleSelectDict('project', index)" :desc="form.skuName"></m-cell> -->
      <m-cell
        title="租户"
        is-link
        @click="handleSelectDict('enterList', '选择租户')"
        :desc="enterList.map[form.tenantId]"
        size="xs"
      ></m-cell>
      <m-cell title="备注" :border="false" size="xs"> </m-cell>
      <m-cell size="xs">
        <m-textarea placeholder="请输入备注" limitPosition="right" v-model="form.summary" style="margin-top: -20rpx" />
      </m-cell>
    </m-cell-group>

    <template v-else>
      <m-cell-group class="box" size="sm" v-for="(item, index) in list" :key="item.skuId || index">
        <m-cell :title="'出库明细' + (index + 1)" weight="title" :border="false" size="xs">
          <template slot="link" v-if="list.length >= 2">
            <m-icon name="mask-close" size="25" @click="handleClickDelete(index)" />
          </template>
        </m-cell>
        <m-cell
          title="SKU名称"
          is-link
          @click="handleSelectDict('skuList', item.skuName || '请选择SKU', index)"
          :desc="item.skuName"
          size="xs"
        ></m-cell>
        <m-cell-group class="box__inner" size="xs">
          <m-cell title="SKU编号">
            <view slot="center" class="center"> {{ skuList.map[item.skuId] }} </view>
          </m-cell>
          <m-cell title="零件图号">
            <view slot="center" class="center">{{ item.skuPartNo }}</view>
          </m-cell>
          <m-cell title="包装数量">
            <view slot="center" class="center"> {{ item.packageNumber || 0 }} </view>
          </m-cell>
        </m-cell-group>
        <m-cell title="出库方式" size="xs">
          <template slot="center">
            <m-radio-group inline v-model="item.roundOut" @change="handleChangeRoundOut(index)">
              <m-radio :label="+item.value" v-for="(item, index) in dicts['out_type'].arr" :key="index">
                {{ item.label }}
              </m-radio>
            </m-radio-group>
          </template>
        </m-cell>
        <m-cell title="出库总数（个）" size="xs">
          <view slot="center" class="center df aic jcsb">
            {{ getTotal(item) }}
            <m-button
              plain
              size="sm"
              @click="handleClickZero(index)"
              :disabled="!item.skuId"
              v-if="item.roundOut === 1"
              background="#fff"
            >
              整出
            </m-button>
          </view>
        </m-cell>
        <m-cell-group size="xs" v-if="item.roundOut === 0" class="box__inner item">
          <m-cell title="整出数量（包）" size="xs">
            <template slot="link">
              <u-number-box
                v-model="item.roundOutQuantity"
                :min="0"
                :press-time="1500"
                :max="Number.MAX_SAFE_INTEGER"
              />
            </template>
          </m-cell>
          <m-cell title="零出数量（个）" size="xs">
            <view slot="center" class="center df aic jcsb">
              {{ item.num || 0 }}
              <m-button plain size="sm" @click="handleClickZero(index)" :disabled="!item.skuId" background="#fff">
                零出
              </m-button>
            </view>
          </m-cell>
        </m-cell-group>
      </m-cell-group>

      <view class="button">
        <m-button
          icon="plus"
          :icon-size="30"
          width="100%"
          background="transparent"
          type="primary"
          size="md"
          plain
          shape="round"
          :disabled="!!getAddSkuDisabled"
          @click="handleClickAdd"
        >
          出库单明细
        </m-button>
      </view>
    </template>

    <out-work-popup
      :visible.sync="visible"
      :num.sync="list[currentIndex].num"
      v-model="list[currentIndex].roundOutStations"
      :sku-id="list[currentIndex].skuId"
      :type="list[currentIndex].roundOut"
    />

    <view style="height: 20rpx"></view>
    <m-fixed>
      <view class="df aic jcsb">
        <m-button width="26%" size="lg" @click="current = 0" v-if="current === 1" plain background="#fff">
          上一步
        </m-button>
        <m-button
          :width="current === 0 ? '100%' : '72%'"
          size="lg"
          @click="handleClickNext"
          :disabled="!!getDisabled"
          :loading="loading"
        >
          {{ current === 0 ? '下一步' : '保存' }}
        </m-button>
      </view>
    </m-fixed>

    <in-work-select-dict-popup
      v-model="selectValue"
      :visible.sync="visible1"
      :title="title"
      :options="getOptions"
      @confirm="handleConfirm"
    />
  </m-container>
</template>

<script>
import { getSku } from '@/api/modules/in-work'
import { AddOutOrder, listConfig, getOutOrder, updateOutOrder } from '@/api/modules/out-work'
import { mapState } from 'vuex'
import dayjs from 'dayjs'
import { showModal } from '@/hooks'
import { router } from '@/router'
import deepClone from '@/utils/deep-clone'
import { useDoingInventory } from '@/hooks'

export default {
  data() {
    return {
      current: 0,
      loading: false,
      form: {
        outOrderCode: '',
        theme: '',
        operName: '',
        auditName: '',
        sourceType: '',
        summary: '',
        remark: '',
        tenantId: '',
      },
      list: [
        {
          roundOut: 0,
          packageQuantity: 1,
          roundOutStations: [],
          roundOutQuantity: 0,
          num: 0,
          imsId: null,
        },
      ],
      currentIndex: 0,
      visible: false,
      isEnableConsumer: false,
      visible: false,
      visible1: false,
      type: 'skuList',
      title: '',
      options: {},
      selectValue: '',
    }
  },
  computed: {
    ...mapState({
      skuList: (state) => state.cache.skuList,
      userList: (state) => state.cache.userList,
      enterList: (state) => state.cache.enterList,
      dicts: (state) => state.outWork.dicts,
      userInfo: (state) => state.login.userInfo,
    }),
    getAddSkuDisabled() {
      return this.list.filter((item) => item.skuId === undefined).length || this.getOptions.length === 0
    },
    getTotal() {
      return (item) => {
        return item.roundOut === 0 ? item.num + item.roundOutQuantity * (item.packageNumber || 1) : item.num
      }
    },
    getDisabled() {
      if (this.current === 0) {
        return false
      }
      return !this.list.every((item) => item.skuId) || this.loading
    },
    getOptions() {
      const arr = this.list.map((item) => item.skuId)
      let data = this[this.type].arr
      if (this.type === 'skuList') {
        return data.filter((item) => !arr.includes(item.value))
      }

      return data
    },
  },
  async created() {
    const outOrderCode = 'IWMS' + dayjs().format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 1000)

    this.form = {
      ...this.form,
      sourceType: Number(this.dicts['out_order_source_type'].arr[0].value),
      outOrderCode,
      theme: 'FUN-' + (dayjs() + '').slice(0, 7) + Math.floor(Math.random() * 1000),
      auditName: this.userInfo.userId + '',
      operName: this.userInfo.userId + '',
      tenantId: this.enterList.arr[0].value,
    }
  },
  async onLoad(options) {
    await useDoingInventory('当前正在执行盘点计划，出库单不会执行')
    this.options = options
    if (options.id) {
      const { data } = await getOutOrder(options.id)
      uni.setNavigationBarTitle({
        title: '修改出库单',
      })
      this.form = data
      this.list = data.imsStockOutOrderDetailList.map((item) => ({
        ...item,
        num: item.skuQuantity - (item.roundOut === 0 ? item.roundOutQuantity : 0),
        roundOutQuantity: item.roundOutQuantity / item.packageNumber,
        roundOutStations: item.roundOutStations.split(',').map((item) => Number(item)),
      }))
    }

    const { rows } = await listConfig({ configKey: 'isEnableConsumer' })
    this.isEnableConsumer = rows.length ? +rows[0].configValue : false
  },
  methods: {
    handleChangeRoundOut(index) {
      this.$set(this.list, index, {
        ...this.list[index],
        roundOutQuantity: 0,
        num: 0,
        roundOutStations: [],
      })
    },
    handleClickDelete(index) {
      showModal({
        title: '删除提示',
        content: '是否确认删除？',
        showCancelButton: true,
        slot: true,
        confirm: () => {
          this.currentIndex = 0
          this.list.splice(index, 1)
        },
      })
    },
    handleClickZero(index) {
      this.currentIndex = index
      this.visible = true
    },
    async handleClickNext() {
      await useDoingInventory('当前正在执行盘点计划，出库单不会执行')
      this.loading = true
      if (this.current === 0) {
        this.current = 1
        this.loading = false
        return
      } else {
        const list = deepClone(this.list)
        for (const item of list) {
          if (item.roundOut === 1 && this.getTotal(item) === 0) {
            uni.showToast({
              title: `${item.skuName} 请选择整出数量`,
              icon: 'none',
            })
            this.loading = false
            return true
          } else if (item.roundOut === 0 && this.getTotal(item) === 0) {
            uni.showToast({
              title: `${item.skuName} 出库数量不能为零`,
              icon: 'none',
            })
            this.loading = false
            return true
          }
        }
        showModal({
          title: '保存提示',
          content: '确认是否保存数据？',
          confirmText: '保存',
          showCancelButton: true,
          confirm: async () => {
            try {
              const form = deepClone(this.form)
              form.status = 5
              form.imsStockOutOrderDetailList = list.map((item) => ({
                ...item,
                roundOutStations: item.roundOutStations.join(','),
                skuQuantity: this.getTotal(item),
                roundOutQuantity: item.roundOutQuantity * item.packageNumber,
              }))
              form.totalQuality = form.imsStockOutOrderDetailList.reduce((pre, curr) => pre + curr.skuQuantity, 0)

              if (this.options.id) {
                await updateOutOrder(form)
              } else {
                await AddOutOrder(form)
              }
              uni.showToast({
                title: '创建成功',
                icon: 'none',
              })
              router.back()
            } catch (e) {}
            this.loading = false
          },
          cancel: () => {
            this.loading = false
          },
        })
      }
    },
    handleClickAdd() {
      this.list.push({
        packageQuantity: 1,
        roundOut: 0,
        roundOutStations: [],
        num: 0,
        roundOutQuantity: 0,
      })
    },
    async handleConfirm(id) {
      if (this.type === 'skuList') {
        const {
          data: { partNo, packageNumber, ...rest },
        } = await getSku(id)

        this.$set(this.list, this.currentIndex, {
          ...(this.list[this.currentIndex] || {}),
          ...rest,
          skuPartNo: partNo,
          packageNumber,
          roundOutQuantity: 0,
          remark: '',
        })
      } else if (this.type === 'userList') {
        this.form.auditName = id
      } else if (this.type === 'enterList') {
        this.form.tenantId = id
      }
    },
    handleSelectDict(type, title, index) {
      if (index !== undefined) {
        this.currentIndex = index
      }

      this.type = type
      this.title = title

      if (type === 'enterList') {
        this.selectValue = this.form.tenantId
      } else if (type === 'userList') {
        this.selectValue = +this.form.auditName
      } else if (type === 'skuList') {
        this.selectValue = this.list[index].skuId
      }
      this.visible1 = true
    },
  },
}
</script>

<style lang="scss" scoped>
.out-work-add {
  .steps {
    margin: 20rpx 0;
    .circle {
      width: 38rpx;
      height: 38rpx;
      background: #c2cdd2;
      color: #fff;
      border-radius: 100rpx;
      &.active {
        background: #248dfa;
      }
    }
  }

  .button {
    padding: 0 30rpx;
  }

  .box {
    .center {
      color: #84898e;
    }
    .disabled {
      background: #f4f8fc !important;
    }

    &__inner {
      ::v-deep {
        .cell {
          &-group__wrap {
            margin: 0;
            background: #f4f8fc;
            border-radius: 0;
          }
          &:after {
            right: 0;
            left: 0;
          }
        }
      }

      &.item {
        ::v-deep {
          .cell {
            &-group__wrap {
              background: #fff;
            }
          }
        }
      }
    }

    ::v-deep {
      .cell {
        &:after {
          border-color: #eaecee;
        }
        .badge {
          width: 200rpx;
        }
      }
      .u-input__input {
        min-height: auto !important;
      }
    }
  }
}
</style>
